package com.um.jdy.platform.platform.manager;

import cn.hutool.core.util.StrUtil;
import com.um.jdy.common.baofu.entity.po.BaofuUser;
import com.um.jdy.common.baofu.service.BaofuService;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.commons.utils.StpKit;
import com.um.jdy.common.device.service.StationSharingService;
import com.um.jdy.common.member.enums.MemberEnum;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.entity.dto.MerchantDTO;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.jdy.common.platform.entity.vo.MerchantVO;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 管理类：平台商家表
 */
@Component
public class MerchantManager extends BaseManager<MerchantService> {

    @Autowired
    StationSharingService stationSharingService;
    @Autowired
    BaofuService baofuService;

    /**
     * 分页查询站场
     * @param params
     * @return
     */
    public Response<Page<Merchant>> getPage(PageParams params){
        Page<Merchant> page = new Page();
        page.setPageNo(params.getPageNo());
        page.setPageSize(params.getPageSize());

        params.getCondition().put("orderby","create_time desc");

        page = service.getPage(page,params.getProperties(),params.getValues(),params.getRangeEntitys(),params.getOrderNames(),params.getSortOns());
        return Response.success(page);
    }

    public Response<List<MerchantVO>> getTopMerchantList(){
        List<Merchant> list = service.getList(new String[]{"type","level",},new Object[]{"merchant",1},new String[]{"create_time"},new String[]{"desc"});
        return Response.success(UMBeanUtils.copyBeanList(list,MerchantVO.class));
    }

    public Response<List<MerchantVO>> getList(String type){
        List<Merchant> list = service.getList(new String[]{"type"},new Object[]{type},new String[]{"create_time"},new String[]{"desc"});
        return Response.success(UMBeanUtils.copyBeanList(list,MerchantVO.class));
    }

    @Transactional
    public Response<Merchant> addEntity(MerchantDTO dto) {

        if(service.getEntity("mobile",dto.getMobile()) != null){
            return Response.failed(PartnersCode.MobileExist);
        }

        Merchant parent = service.getEntity(dto.getParentId());
        if(parent != null && parent.getCommissionRate() < dto.getCommissionRate()){
            if(dto.getType().equals(MemberEnum.UserType.merchant.name())) {
                throw new ServiceException(PartnersCode.RateNotLargeThanParent);
            }else{
                throw new ServiceException(PartnersCode.RateNotLargeThanParentMerchant);
            }
        }

        Merchant entity = UMBeanUtils.copyBean(dto, Merchant.class);
        if(entity.getType().equals(MemberEnum.UserType.merchant.name())) {
            if (StringUtil.getTrim(entity.getParentId()).equals("")) {
                entity.setLevel(1);
            } else {
                entity.setLevel(2);
            }
        }
        //宝付用户验证
        if(StrUtil.isBlank(dto.getBaofuUserId())){
            throw new ServiceException(PartnersCode.BaofuNotExist);
        }
        BaofuUser baofuUser = baofuService.getEntity(dto.getBaofuUserId());
        if(baofuUser == null){
            throw new ServiceException(PartnersCode.BaofuNotExist);
        }

        String pwd = RSAUtil.simpleDecrypt(dto.getPassword());
        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);
        String encryptPwd = des.encrypt(pwd);

        entity.setPassword(encryptPwd);
        entity.setCreateTime(new Date());
        return Response.success(service.addEntity(entity));
    }

    @Transactional
    public Response<Merchant> updateEntity(String id, MerchantDTO dto) {
        Merchant parent = service.getEntity(dto.getParentId());
        if(parent != null && parent.getCommissionRate() < dto.getCommissionRate()){
            if(dto.getType().equals(MemberEnum.UserType.merchant.name())) {
                throw new ServiceException(PartnersCode.RateNotLargeThanParent);
            }else{
                throw new ServiceException(PartnersCode.RateNotLargeThanParentMerchant);
            }
        }


        List<Merchant> list = service.getList("parent_id",id);

        int rate = 0;
        for(Merchant item : list){
            rate = Math.max(rate,item.getCommissionRate());
        }

        if(dto.getCommissionRate() < rate){
            throw new ServiceException(PartnersCode.RateNotLessThanChild);
        }

        Merchant entity = service.getEntity(id);
        BeanUtils.copyProperties(dto, entity);
        return Response.success(this.service.updateEntity(entity));
    }

    public Response enable(String id, String enable) {
        Merchant entity = this.service.getEntity(id);
        if(entity == null){
            throw new ServiceException(PartnersCode.PartnersNotExist);
        }

        entity.setIsEnable(enable);
        boolean result = this.service.update(entity);
        if(result && YesOrNo.No.name().equals(enable)){
            StpKit.MERCHANT.logout(id);
        }
        return result ? Response.success() : Response.failed();
    }

    public Response delete(String id) {
        Merchant merchant = service.getEntity(id);
        if(StringUtil.equals(merchant.getType(),MemberEnum.UserType.sharing.name())){
            stationSharingService.delete("platform_merchant_id",id);
        }
        boolean result = this.service.delete(id);
        return result ? Response.success() : Response.failed();
    }

    @Transactional
    public Response deleteIds(List<String> ids) {
        for(String id : ids){
            Merchant merchant = service.getEntity(id);
            if(StringUtil.equals(merchant.getType(),MemberEnum.UserType.sharing.name())){
                stationSharingService.delete("platform_merchant_id",id);
            }
        }
        boolean result = service.deleteIds(ids);
        return result ? Response.success() : Response.failed();
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    public Response resetPassword(String userId,String password){
        Merchant entity = service.getEntity(userId);
        if(entity == null){
            throw new ServiceException(PartnersCode.PartnersNotExist);
        }

        String pwd = RSAUtil.simpleDecrypt(password);
        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);
        String encryptPwd = des.encrypt(pwd);
        if(encryptPwd.equals(entity.getPassword())){
            throw new ServiceException(PartnersCode.PwdSame);
        }

        entity.setPassword(encryptPwd);
        boolean result = service.update(entity);
        return result ? Response.success() : Response.failed();
    }

}
